package com.example.demo.service.impl;

import com.example.demo.entity.Permissions;
import com.example.demo.entity.RolePermissions;
import com.example.demo.entity.User;
import com.example.demo.service.PermissionsService;
import com.example.demo.service.RolePermissionsService;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserService userService;
    @Autowired
    private RolePermissionsService rolePermissionsService;
    @Autowired
    private PermissionsService permissionsService;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("Loading user by username: {}", username);
        User temp = new User();
        temp.setUsername(username);
        //根据用户名查询用户
        User user = userService.getUser(temp);
        if (user == null) {
            logger.error("User not found with username: {}", username);
            throw new UsernameNotFoundException("用户名不存在");
        }
        logger.info("Found user: {}", user);
        //从角色权限关联表，获取角色权限id列表
        List<RolePermissions> list = rolePermissionsService.getList(user.getRoleId());
        logger.info("Role permissions list: {}", list);
        List<Integer> idlist = new ArrayList<>();
        for (RolePermissions rolePermissions : list) {
            idlist.add(rolePermissions.getPermissionId());
        }
        logger.info("Permissions Id list: {}", idlist);
        //根据角色权限id列表获取权限列表
        List<Permissions> permissionsList = permissionsService.getPermissions(idlist);
        logger.info("Permissions list: {}", permissionsList);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //将权限添加到authorities中
        for (Permissions permissions : permissionsList) {
            authorities.add(new SimpleGrantedAuthority(permissions.getName()));
        }
        logger.info("Authorities: {}", authorities);
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }
}